<template>
  <div>
    <!-- 输入内容查询位置 -->
    <el-input v-model="username" placeholder="用户名" style="width:150px" @keyup.enter.native="handleSearch"></el-input>
    <el-button type="primary" size="default" icon="el-icon-search" style="margin-left:20px;" @click="handleSearch">查询</el-button>
    <el-button type="plain" size="default" @click="handleClear">清空</el-button>
    <!-- 添加和批量删除位置 -->
    <div style="margin:20px 0px;">
      <el-button type="primary" size="default" @click="handleAddUser" >添加</el-button>
      <el-popconfirm
        confirmButtonText='确定'
        cancelButtonText='考虑考虑'
        icon="el-icon-info"
        iconColor="red"
        title="这是一段内容确定删除吗？"
        @onConfirm="deleteAll"
      >
      <el-button slot="reference"  :disabled="idList.length >0 ?  false : true" size="default" type="danger"  >批量删除</el-button>
      </el-popconfirm>
    </div>

  <!-- 打开对话框  添加和修改的对话框 -->
    <el-dialog title="添加用户" :visible.sync="dialogFormVisible">

      <el-form :model="form" label-width="80px" :rules="rules" ref="tmForm">
        <el-form-item label="用户名" prop="userName" >
          <el-input v-model="form.userName" ></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickName" >
          <el-input v-model="form.nickName"  ></el-input>
        </el-form-item>
         <el-form-item label="用户密码" prop="password" v-if="isAdd">
          <el-input v-model="form.password" ></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>


    <!-- 分配权限的对话框 -->
    <el-dialog title="设置角色" :visible.sync="dialogRole">
      <el-form :model="Roleform">

        <el-form-item label="用户名" label-width="100px">
          <el-input v-model="Roleform.userName"  disabled></el-input>
        </el-form-item>

        <el-form-item label="角色列表" label-width="100px">
            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
            <div style="margin: 15px 0;"></div>
            <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
              <el-checkbox v-for="city in cities" :label="city.id" :key="city.id">{{city.roleName}}</el-checkbox>
            </el-checkbox-group>

        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogRole = false">取 消</el-button>
        <el-button type="primary" @click="handleSaveRole">保存</el-button>
      </div>
    </el-dialog>

    <!-- 表格位置 -->
    <el-table :data="userList"  border stripe style="margin:20px 0px;" v-loading="loading"  @selection-change="handleSelectionChange">
      <el-table-column type="selection"></el-table-column>
      <el-table-column label="序号" width="80px" align="center" type="index"></el-table-column>
      <el-table-column label="用户名" prop="username" width="80px"></el-table-column>
      <el-table-column label="用户昵称" prop="nickName" width="80px"></el-table-column>
      <el-table-column label="权限列表" prop="roleName"></el-table-column>
      <el-table-column label="创建时间" prop="gmtCreate"></el-table-column>
      <el-table-column label="更新时间" prop="gmtModified"></el-table-column>
      <el-table-column label="操作" width="200px">
        <template slot-scope="{row,$index}">
          <HintButton @click="assignRole(row)" icon="el-icon-user-solid" size="mini" type="info" info="分配角色" style="margin-left:10px;" />
          <HintButton @click="handleEdit(row)" icon="el-icon-edit" type="primary" size="mini" info="修改用户" style="margin-left:10px;"/>

          <el-popconfirm
            confirm-button-text='确定'
            cancel-button-text='考虑考虑'
            icon="el-icon-info"
            icon-color="red"
            title="这是一段内容确定删除吗？"
            @onConfirm="handleDelete(row)"
          >
          <HintButton icon="el-icon-delete" slot="reference" type="danger" size="mini" info="删除用户" style="margin-left:10px;"/>
          </el-popconfirm>

        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器位置 -->
    <el-pagination
      @size-change="sizeChange"
      @current-change="currentChange"
      :current-page.sync="currentPage"
      :page-sizes="[3, 5, 10, 20]"
      :page-size="pageSize"
      layout=" prev, pager, next, jumper,-> ,sizes,total"
      :total="totalNum" 
      background
      :pager-count="7">
    </el-pagination>
    
   
    
  </div>
</template>

<script>
import dayjs from 'dayjs'
// 定义用户名的校验规则
const validateUserName = (rule, value, callback)=>{
  const reg = /^[A-Za-z0-9_\u4e00-\u9fa5]{4,16}$/
  if(reg.test(value)){
    callback()
  }else{
    callback(new Error('请输入4-16位之间的用户名，不能带有特殊符号哦~'))
  }
}
// 定义输入密码的校验规则
const validatePassword = (rule,value,callback)=>{
  const reg = /^(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9~!@&%#_]{8,16}$/
  if(reg.test(value)){
    callback()
  }else{
    callback(new Error('密码必须包含一个大写，一个小写字母，且长度为8到16位哦~'))
  }
}


  export default {
    name:'User',
    data() {
      return {
        dialogRole:false,   //分配权限的dialog 默认是false'
        isAdd:true,    //dialog对话框里密码行 是否显示
        username:'',   //用户输入的查询内容
        pageSize:3,  //一页展示多少条数据
        totalNum:50, //总共有多少条数据
        currentPage:1, //当前页
        userList:[],   //当前页的用户列表数据
        loading:false,  //loading表格的loading效果
        dialogFormVisible:false,   //对话框默认是关闭的状态
        gmtCreate:'',             //当前用户的创建时间
        userId:'',                //修改当前用户的id
        roleName:'',              //当前用户的权限
        salt:'',                  //用户创立的年份
        password:'',              //用户密码
        idList:[],                //批量删除的数组 之后要整理id 提交个服务器
        form:{               //form表单收集数据
          userName:'',
          password:'',
          nickName:''       //dialog表单中收集的用户别名
        }, 
        Roleform:{           //收集设置角色的数据
          userName:'',
          userID:''           //操作分配属性当前的用户id
        },       
        rules:{
          userName:[
            { validator: validateUserName,required: true,trigger: 'blur'}
          ],
          password:[
            { validator: validatePassword,required: true,trigger: 'blur'}
          ]
        },
        checkAll: false,                       //角色列表都选中
        checkedCities: [],                      //选中的角色列表数据
        checkedAllCities:[],                   //所有都选中的话数组列表
        cities:[],                             //所有列表选数据
        isIndeterminate: true ,               //是否全选
        allRolesList:[],                      //所有角色的数据列表
        assignRoles:[],                       //目前已经有的角色列表
      
      }
    },
    computed:{
      // 所有列表数据
      // cities(){
      //   const arr = []
      //    this.allRolesList.forEach((item)=>{
      //     arr.push(item.roleName)
      //    })
      //    return arr
      // }
    },
    methods:{
      // 当前页面显示几条数据
      sizeChange(pageSize){
        this.pageSize =pageSize
        this.getUserList()
      },
      // 当前的页码是多少
      currentChange(currentPage){
        this.currentPage = currentPage
        // 再次获取当前页用户数据
        this.getUserList()
      },
      // 获取用户列表数据
     async getUserList(){
      this.loading = true
      const {currentPage,pageSize,username} = this
      const searObj = {
        username:username.trim(),
        nickName:''
      }
      const result = await this.$ajax.userInfo.reqGetUserList(currentPage,pageSize,searObj)
      if(result.code == 20000){
        this.userList = result.data.items
        this.totalNum = result.data.total
        this.loading = false
      }
      },
      // 查询用户列表数据
      handleSearch(){
        this.getUserList()
      },
      // 清空用户搜索数据
      handleClear(){
        this.username = ''
        // 再获取一下用户列表数据
        this.getUserList()
      },
      // 打开添加用户的dialog
      handleAddUser(){
        this.dialogFormVisible = true
        //  // 初始数据置为空
        // this.form.userName = ''
        // this.form.nickName = ''
        // this.form.password = ''
        // 重置表单
        this.$nextTick(()=>{
          this.$refs.tmForm.resetFields()
        })
      },
      // 新增和修改 提交表单
      submitForm(){
        // console.log(111)
        this.$refs.tmForm.validate((success)=>{
 
          if(success){
            // 表单验证符合条件 发请求 将数据添加到服务器 
             this.addOrupdateUser()
           
            // 添加成功之后 关闭dialog
            // this.$message('添加用户成功~')
          }else{
            return false
          }
        })
      },
      // 添加或者修改用户列表数据  发请求
     async addOrupdateUser(){
      const time = dayjs().format('YYYY-MM-DD HH:mm:ss')
      let year = time.slice(0,4)
      const data = {
        "deleted": false,
        "gmtCreate":this.gmtCreate || time,
        "gmtModified": time,
        "id": this.userId ,
        "nickName": this.form.nickName,
        "password":this.password || this.form.password,
        "roleName": this.roleName,
        "salt":this.salt || year,
        "token": "",
        "username":this.form.userName
      }
      
      const result = await this.$ajax.userInfo.reqAddOrUpdateUser(data)
      // console.log(result)
      if(result.code == 20000){
       // 提示用户 添加成功 || 修改用户成功
        if(data.id){
        this.$message.success('修改用户成功')
        }else{
        this.$message.success('添加用户成功')
        }
        // 获取最新用户列表数据
        this.getUserList()
        // 关闭对话框
        this.dialogFormVisible = false
      }else{
        this.$message.warning(result.message || '修改失败，请稍后重试~')
      }
      },
      // 点击修改用户按钮的时候
      handleEdit(row){
        // dialog对话框弹出来
        this.dialogFormVisible = true
        // 初始数据置为空
        this.form.userName = ''
        this.form.nickName = ''
         // 重置表单
        this.$nextTick(()=>{
          this.$refs.tmForm.resetFields()
        })
        
        // 对话框里面密码内条 要隐藏
        this.isAdd = false
        // data里面的数据要用row修改
        // console.log(row)
        this.gmtCreate = row.gmtCreate
        this.userId = row.id
        this.password = row.password
        this.roleName = row.roleName
        this.salt = row.salt
      },
      // 点击删除当前的这个用户
     async handleDelete(row){
        const result = await this.$ajax.userInfo.reqRemoveUser(row.id)
        // console.log(result)
        if(result.code == 20000){
          this.$message.success('删除数据成功')
          // 再次获取用户列表数据
          this.getUserList()
        }else{
          this.$message.warning(result.message || '删除数据失败，稍后再试~')
        }
        // 发请求
      },
      // 当用户选中切换的时候
      handleSelectionChange(val){
        this.idList = val
      },
      // 批量删除的回调
     async deleteAll(){
        // id数组
        const arr = []
        this.idList.forEach((item)=>{
          arr.push(item.id)
        })
      //  发请求
      const result = await this.$ajax.userInfo.reqDeleteAll(JSON.stringify(arr))
      if(result.code == 20000){
        this.$message.success('删除成功')
        this.getUserList()
      }else{
        this.$message.warning(result.message || '删除失败请稍后重试哦~')
      }
      },
      // 点击分配角色
     async assignRole(row){
      // console.log(row)
        this.dialogRole = true
        this.Roleform.userName  = row.username
        this.Roleform.userID = row.id
        // 发请求获取所有角色列表的数据
        const result = await this.$ajax.userInfo.reqGetRoleList(row.id)
        // console.log(result)
        if(result.code == 20000){
          // 将来用来遍历的数组
          this.cities = result.data.allRolesList
          // 选中的数组列表   --这里不能是对象  要改成 id列表
          const arr = []
          result.data.assignRoles.forEach((item)=>{
            arr.push(item.id)
          })
          this.checkedCities = arr 
          // 全选的id列表
          const arr1 = []
            result.data.allRolesList.forEach((item)=>{
            arr1.push(item.id)
          })
          this.checkedAllCities = arr1 

        }else{
          this.$message.warning(result.message)
        }
      },
      // 处理全选的改变
       handleCheckAllChange(val) {
        // console.log(val)
        // val  shi   true   或者  false
        this.checkedCities = val ? this.checkedAllCities : [];
        // console.log()
        this.isIndeterminate = false;
      },
      // 处理单个选中和不选中
      handleCheckedCitiesChange(value) {
        // value 是label绑定的值的数组
        // console.log(value)
        // 已选数组的长度
        let checkedCount = value.length;
        // 已选数组的长度是不是等于所有角色列表的长度  决定 全选 还是全不选的  true  或  false
        this.checkAll = checkedCount === this.cities.length;
        // 决定横杠的显示
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
      },
      // 保存对用户角色的添加
     async handleSaveRole(){
        // 关闭对话框
        this.dialogRole = false
        const rolesStr = this.checkedCities.join(',')
        // 发请求
       const result = await  this.$ajax.userInfo.reqAssignRole(this.Roleform.userID,rolesStr)
      //  console.log(result)
       if(result.code == 20000){
        this.$message.success('修改用户角色成功~')
        // 刷新数据
        this.getUserList()
       }else{
        this.$message.warning(result.message || '修改失败请稍后重试~')
       }
      }
    },

  
    mounted(){
      this.getUserList()
    }
  }
</script>

<style lang="less" scoped>
  
</style>